package com.antu.first.service.impl;

import com.antu.first.bean.Comment;
import com.antu.first.dao.CommentDao;
import com.antu.first.dto.CommentOperationExecution;
import com.antu.first.enums.CommentStateEnum;
import com.antu.first.exceptions.CommentOperationException;
import com.antu.first.service.CommentService;
import com.antu.first.util.PageCaculator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/3/6.
 */
@Service
public class CommentServiceImp implements CommentService {

    @Autowired
    private CommentDao commentDao;

    @Override
    public CommentOperationExecution queryAllComment(int hId, int coType, int pageIndex) {
        try {
            //统计该条件下的所有评论数量
            int count = commentDao.countComment(hId, coType);
            //如果传入的页数大于或者等于数据库中记录的总分页数，则返回一个提示信息
            if(pageIndex > (count/10)+1){
                return new CommentOperationExecution(CommentStateEnum.IS_LAST_PAGE);
            }else{
                //否则直接进行查询，并根据查询结果返回相应内容
                //计算当前的记录该从第几条记录开始获取
                int rowIndex = PageCaculator.caculateRowIndex(pageIndex, 10);
                List<Comment> comments=commentDao.queryAlls(hId, coType, rowIndex);
                if (comments.size() > 0) {
                    CommentOperationExecution execution = new CommentOperationExecution(CommentStateEnum.SUCCESS, comments);
                    execution.setCount(count);
                    return execution;
                }else if(comments.size() == 0) {
                    return new CommentOperationExecution(CommentStateEnum.EMPTY_LIST);
                }else{
                    return new CommentOperationExecution(CommentStateEnum.ERROR);
                }
            }
        } catch (Exception e) {
            throw new CommentOperationException("获取评论列表的过程中出错，错误信息："+e.getMessage());
        }
    }

    @Override
    public CommentOperationExecution addComment(Comment comment) {
        //新增评论的方法，需要传入的值包括评论内容、用户Id、酒店Id、订单Id、评论星级、评论类型
        try{
            if(comment.getCoContent() == null || "".equals(comment.getCoContent())){
                return new CommentOperationExecution(CommentStateEnum.EMPTY_CONTENT);
            }
            comment.setCoTime(new Date());
            int effectNum = commentDao.addComment(comment);
            if(effectNum != 1){
                return new CommentOperationExecution(CommentStateEnum.FAILED);
            }
        }catch(Exception e){
            throw new CommentOperationException("CommentService-addComment,在添加评论的过程中发生异常，异常信息："+e.getMessage());
        }
        return new CommentOperationExecution(CommentStateEnum.COMMENT_SUCCESS, comment);
    }
}
